<template>
    <div class="sure-order">
        <div class="user-box">
            <div class="user-wmsg displayFlex">
                <div class="flex1 user-msg" @click="selectAdress">
                    <div class="user-other-msg displayFlex width-full justifyCtBwt flex-algin-center">
                        <span class="user-name">{{sendWay.name}}</span>
                        <span class="phone-num displayFlex flex-algin-center">{{sendWay.phone}}</span>
                        <span>
                            <span class="send-way-text" v-if="sendWay.defaultOne">默认</span>
                            <span class="send-way-text send-active" v-if="sendWay.curDeliveryType == 1">快递</span>
                            <span class="send-way-text self-extract" v-else>自提</span>
                        </span>
                    </div>
                    <p class="user-address" v-if="sendWay.curDeliveryType == 1 && sendWay.address">
                        {{sendWay.address}}
                    </p>
                </div>
                <div class="assass-box displayFlex flex-algin-center">
                    <span class="iconfont icon-arrows_right"></span>
                </div>
            </div>
        </div>
        <select-cart
                v-if="sureOrder && Object.keys(sureOrder).length > 0"
                @selectedDiscount="showDiscountFn"
                @closeSlideBottom="discountMsg.show = false"
                @refreshBuyBar="refreshBuyBar"
                @freshCartMoudleMsg="freshCartMoudleMsg"
                :cartMoudleProp="sureOrder"
        ></select-cart>
        <buy-bar :buyBarProp="buyBarMsg"
                 @toPay="selectPayWay"></buy-bar>
        <slide-bottom v-if="discountMsg.show" ref="discountList" @closeSlideBottom="closeSelectDiscount">
            <!--<div class="card-tab displayFlex justifyCtArd">-->
            <!--<span class="tab-item">可用（2）</span>-->
            <!--<span class="tab-item" :class="{'active':true}">-->
            <!--不可用(1)-->
            <!--</span>-->
            <!--</div>-->
            <tap-banner
                    v-if="Object.keys(tabBanner).length > 0"
                    @tapItem="selectDisount"
                    :bannerProps="tabBanner"
            ></tap-banner>
            <scroller
                    v-for="(value,key) in tabBanner.list"
                    v-if="discountMsg.tapId == value.id"
                    ref="myscroller"
                    :key="key"
                    :on-refresh="refresh"
                    :on-infinite="infinite">
                <ul class="coupons1_0-list" v-if="((discountMsg.tapId == 0 && Array.isArray(discountlist.canUseList) && discountlist.canUseList.length > 0) || (discountMsg.tapId == 1 && Array.isArray(discountlist.cantUseList) && discountlist.cantUseList.length > 0))">
                    <li class="coupons1_0-item" v-for="cartStoreInfo in sureOrder.cartStoreInfos"
                        v-if="(cartStoreInfo.storeId == discountMsg.storeId)">
                        <!--<router-link class="" :to="{path:'/card/detail',query:{ticketNum:value && value.ticketNum ? value.ticketNum : 0}}">-->
                        <span v-if="discountMsg.tapId == 0 && Array.isArray(discountlist.canUseList) && discountlist.canUseList.length > 0">
                             <span v-for="ticketValue in discountlist.canUseList" @click="selectDisountItem(discountMsg.storeId,ticketValue)">
                                <card-item :cardItemMsgProps="cardItemFn(ticketValue)" v-if="value.num"></card-item>
                             </span>
                        </span>
                        <span class="disabled-ticket" v-if="discountMsg.tapId == 1 && Array.isArray(discountlist.canUseList) && discountlist.canUseList.length > 0">
                             <span v-for="ticketValue in discountlist.cantUseList">
                                <card-item :cardItemMsgProps="cardItemFn(ticketValue)" v-if="value.num"></card-item>
                             </span>
                        </span>
                        <!--</router-link>-->
                    </li>
                </ul>
                <div class="coupons1_0-list" v-else>
                    <no-data :noDataProps="{text:'没有优惠券'}"></no-data>
                </div>
            </scroller>
        </slide-bottom>
        <!--支付方式选择的弹窗-->
        <slide-bottom v-if="payWayAlert" ref="payWay">
            <pay-way
                    :payWayProp="payWay"
                    @toPay="surePayWay"
                    @colsePayWay="colsePayWay"
            ></pay-way>
        </slide-bottom>
        <!--输入密码的弹窗-->
        <div class="input-password-wrap">
            <slide-bottom v-if="inputPassword" ref="inputPassword">
                <input-password
                        ref="inputPasswordAlert"
                        @closeInputPassword="closeInputPassword"
                        @submitPassword="toPay"></input-password>
            </slide-bottom>
        </div>
        <!--淡入淡出的蒙版-->
        <transition name="border"
                    enter-active-class="animated fadeIn"
                    leave-active-class="animated fadeOut">
            <v-bord v-if="slideShow">
                <div slot="cantClick" @click="showSelefCenter(false)" class="com_black"></div>
            </v-bord>
        </transition>
    </div>
</template>

<script>
    import MD5 from "js-md5";
    import XPay from '../../x/XPay'


    export default {
        name: "SureOrder",
        data() {
            return {
                slideShow: false,
                payWayAlert: false,//选择支付方式的弹框
                inputPassword: false,//输入密码的弹框
                payWay: {},//支付方式选择需要的参数
                tabBanner: {},//优惠券切换的tab
                buyBarMsg: {},//底部购买条需要的参数
                discountMsg: {
                    isShow: false,//优惠券选项弹框是否显示
                    tapId: 0,
                    storeId: 0,
                },
                discountlist: {/*优惠券列表*/
                    canUseList: [],
                    cantUseList: []
                },
                selectedStoreGoods: [{
                    storeId: 0,
                    ids: [],
                    goodsList: [
                        {
                            itemId: 0,
                            styleName: '',
                            price: 0,
                        }
                    ]
                }],//选择优惠券时选择店铺中的商品id
                cardItems: [],//优惠券列表
                sendWay: {//配送信息
                    //     "id":45,                        //-------配送ID
                    //     "name":"启明",                  //-------收货人名字
                    //     "phone":"15919467391",          //-------收货人手机号码
                    //     "address":"田贝三路明阳酒店",  //-------收货地址
                    //     "defaultOne":true,              //-------是否默认
                    //     "selected":true                 //-------是否当前选择
                },
                sureOrder: {
                    // "deliveryType": 0,                      //-------配送类型  0:自提  1:快递
                    // "deliveryId": 115,                          //-------当前的配送ID
                    // "deliveryName": "启明",                   //-------配送人姓名
                    // "deliveryPhone": "15919467391",         //--------配送人手机号码
                    // "cartStoreInfos": [                      //-------结算店铺列表
                    //     {
                    //         "storeId": 102,         //--------店铺ID
                    //         "storeName": "王者动物园",     //------店铺名字
                    //         "storeLogo": "https://oss.pg.yibaotong.top/th1a365d0.png",  //-----店铺logo
                    //         "supportExpress": true,     //---------是否支持快递
                    //         "expressFreight": "23",     //---------店铺快递运费
                    //         "cartItemInfos": [       //-------店铺采购商品列表
                    //             {
                    //                 "itemId": 124,
                    //                 "itemImg": "https://oss.pg.yi/135100.png",   //------商品图片
                    //                 "itemTitle": "磕破一卡通卡关于推进",      //-------商品标题
                    //                 "styleName": "a",       //-------当前款式
                    //                 "buyNum": 2,        //------购买数量
                    //                 "price": "100",     //------用户已选购的商品单价
                    //                 "depositRate": "1.0",   //--------商品保证金比例,
                    //                 "saleMode": 1,          //-----------售出方式 0-单款  1-多款
                    //                 "maxBuyNum": 5,          //------------个人可购买的最大数量(单款有效)
                    //                 "maxWarn": "此商品限购5件",          //------------超过最大购买数时的预警文案(单款有效)
                    //                 "itemServerals": [
                    //                     {
                    //                         "styleName": "a",               //-----------款名
                    //                         "styleImg": "https://oss.pg.yibao/100.png",         //-----------款式图
                    //                         "price": "100",         //-----------售价
                    //                         "quantity": 484,        //-----------款库存,为0则置灰
                    //                         "maxBuyNum": 5,         //------------个人可购买的最大数量
                    //                         "maxWarn": "此商品限购5件"         //------------超过最大购买数时的预警文案
                    //                     }
                    //                 ]
                    //             }
                    //         ],
                    //         "defaultUseTicket": {           //-----------默认使用的用户优惠券
                    //             "ticketNum": "COOC5L99ZO",          //----------用户券号
                    //             "ticketType": 1,            //------优惠券类型 1: 代金券  2: 增值券 3:折扣券  4:赠品券
                    //             "ticketContent": {          //-----票的内容,详细参数 (券类型不同,内容不同)  @券的内容
                    //                 "@class": "com.yibaotong.ms.nw.coupon.BO.user.content.ticket.TicketCashJson",
                    //                 "limitConsume": false,
                    //                 "consumePrice": "0",
                    //                 "cashPrice": "100"
                    //             },
                    //             "state": 0,     //-------用户券状态，-2：失效，-1 :未开启 , 0 : 正常
                    //             "startTime": "19/07/19 11:18",      //-------生效时间
                    //             "endTime": "19/07/26 11:18",        //-------结束时间
                    //             "storeIcon": "https://oss.pg.yib/365d0.png",        //-------门店图标
                    //             "threshold": "无门槛直减",     //--------消费门槛展示文案
                    //             "scope": "全部商品可用",          //--------限定范围
                    //             "onlyOfflineUse": false,        //--------是否仅线下核销
                    //             "canUseItemIds": null,          //------指定消费的商品列表，为空或null表示所有商品可用
                    //             "deliveryTypes": [              //------可使用的配送方式列表 0:到店提货  1:同城快递
                    //                 0,
                    //                 1
                    //             ]
                    //         },
                    //         "tradeTicketModels": [      //----------用户的优惠券列表
                    //             {
                    //                 "ticketNum": "COOC5L99ZO",
                    //                 "ticketType": 1,
                    //                 "ticketContent": {
                    //                     "@class": "com.yibaotong.ms.nw.coupon.BO.user.content.ticket.TicketCashJson",
                    //                     "limitConsume": false,
                    //                     "consumePrice": "0",
                    //                     "cashPrice": "100"
                    //                 },
                    //                 "state": 0,
                    //                 "startTime": "19/07/19 11:18",
                    //                 "endTime": "19/07/26 11:18",
                    //                 "storeIcon": "https://oss.pg.yibaoton/a365d0.png",
                    //                 "threshold": "无门槛直减",
                    //                 "scope": "全部商品可用",
                    //                 "onlyOfflineUse": false,
                    //                 "canUseItemIds": null,
                    //                 "deliveryTypes": [
                    //                     0,
                    //                     1
                    //                 ]
                    //             }
                    //         ],
                    //         "reduceInfos": [        //------------采购结算优惠信息。
                    //             //这里仅考虑 0:一起购优惠  2:会员折扣  4:团长优惠  5:排名优惠  6:抽奖中奖优惠
                    //             //1:优惠券  3:会员积分抵现  7:红包抵扣  由客户端来添加删除
                    //             {
                    //                 "type": 0,          //-----------优惠类型  0:一起购优惠  2:会员折扣  4:团长优惠  5:排名优惠  6:抽奖中奖优惠
                    //                 "conditions": [     //-------享受该优惠必须同时满足的条件列表 ，为空表示无其他任何条件
                    //                     {
                    //                         "itemId": 124,      //---------必须购买的商品ID (为空则不必须)
                    //                         "styleName": null   //---------必须购买的商品款式  (为空则不必须)
                    //                     },
                    //                     {
                    //                         "itemId": 144,
                    //                         "styleName": null
                    //                     }
                    //                 ],
                    //                 "reduceContent": {          //--------优惠内容
                    //                     "name": "一起购优惠",      //-------优惠显示名字
                    //                     "valueType": 0,         //-------优惠数值类型 0：金额  1：折扣
                    //                     "value": "5",           //-------优惠数值,折扣的数值范围为0-1，计算优惠取  目标商品总价*(1-优惠数值)
                    //                     "targetItemIds": [      //-------计算优惠的目标商品ID列表，为空则直接在总价上进行计算
                    //                         124,
                    //                         144
                    //                     ],
                    //                     "accumulative": true    //------优惠是否可按购买数量累加，目标商品多个，则取购买的最小值
                    //                 }
                    //             }
                    //         ]
                    //     }
                    // ]
                },
            }
        },
        mounted() {
            this.init();
        },
        computed: {
            currentUser(){
                return this.$store.getters.currentUserFn;
            },
            currentThird() {
                return this.$store.getters.currentThirdFn;
            },
            // ...mapGetters({'sendWay':'getSendWayMsg'}),
        },
        methods: {
            init() {
                let that = this;
                /*购物车结算页面*/
                let sureOrderMsg = window.sessionStorage.getItem('sureOrderMsg') ? JSON.parse(window.sessionStorage.getItem('sureOrderMsg')) : {}
                let params = {
                    "userId": that.currentUser && that.currentUser.userId ? that.currentUser.userId : 0,
                };
                params = Object.assign({}, params, sureOrderMsg)
                // {
                //     "userId": that.userId,          //-----用户ID
                //     "procureItems": [
                //         {
                //             "itemId": 124,       //-------购买的商品ID
                //             "styleName": "a",        //-------购买的商品款式
                //             "buyNum": 2           //-------购买的商品数量
                //         }
                //     ]
                // };
                let url = `${this.NW_API_API_LOCALE_VERSION}/trade/confirm/procure`
                this.xurl.postDataJsonLoading(url, params).then((data) => {
                    if (data.success) {
                        let tempObj = {
                            noSelectBtn: true,
                            needDiscount: true,
                        };
                        data.result.procureStores.forEach((value, index) => {
                            data.result.procureStores[index]["cartItemInfos"] = value.procureItems;
                            delete data.result.procureStores[index].procureItems;
                        });
                        data.result["cartStoreInfos"] = data.result.procureStores;
                        delete data.result.procureStores;
                        tempObj = Object.assign({}, tempObj, data.result);
                        this.sureOrder = tempObj;
                        /*初始化配送信息*/
                        this.initSendWayMsg();

                        /*TODO 初始化优惠信息*/

                        /*初始化底部购买条*/
                        this.initBuyBar();
                    } else if (data.errMsg) {
                        this.$root.$emit('toast', {msg: data.errMsg});
                    } else {
                        this.$root.$emit('toast', {msg: '获取订单信息失败'});
                    }
                })
            },
            closeSelectDiscount(){
                setTimeout(()=>{
                    let tempObj = {
                        show:false,
                        tapId: 0,
                        storeId: 0,
                    }
                    this.discountMsg = Object.assign({},this.discountMsg,tempObj);
                },500)
            },
            initBuyBar() {
                let tempObj = {
                    noSelectBtn: true,//不需要选择按钮
                    selectAll: false,//是否全选
                    deposit: {
                        isShow: true,
                        money: 0,
                    },
                    btnText: '去支付',
                    totalMoney: 0,//总金额
                    payMoney: {
                        money: 0,
                        text: '定金'
                    },//商品总金额
                    shippingFee: {
                        isShow: false,
                        money: 0,
                    },//邮费、配送费用
                    warnText: '',
                }
                this.buyBarMsg = Object.assign({}, this.buyBarMsg, tempObj);
            },
            refreshBuyBar(obj) {
                this.buyBarMsg = Object.assign({}, this.buyBarMsg, obj);
            },
            freshCartMoudleMsg(obj){
                this.sureOrder = Object.assign({},this.sureOrder,obj)
            },
            showSelefCenter(boolean) {
                this.slideShow = boolean;
            },
            initSendWayMsg() {
                let that = this;
                let isALlStoreSupportExpress = true;
                for (let value of that.sureOrder.cartStoreInfos) {
                    if (!value.supportExpress) {
                        isALlStoreSupportExpress = false;
                        break;
                    }
                }
                //这里去vuex里面
                let params = {
                    "userId": that.currentUser && that.currentUser.userId ? that.currentUser.userId : 0,          //----------用户ID
                    "supportExpress": isALlStoreSupportExpress,      //--------是否全部店铺支持快递
                    "curDeliveryType": 0,        //--------当前配送类型  0：自提   1：快递
                    "curDeliveryId": that.sureOrder.deliveryId          //--------当前配送ID
                };
                this.$store.commit('orderSendWay', params);
                /*ajax已经获取到数据了*/
                setTimeout(() => {
                    /*获取了配送方式之后*/
                    let sendWay = this.$store.getters.getSendWayMsg;
                    if (sendWay.curDeliveryType == 0 && Array.isArray(sendWay.pickupPersons) && sendWay.pickupPersons.length > 0) {
                        sendWay.pickupPersons.forEach((value, index) => {
                            if (value.selected) {
                                that.sendWay = Object.assign({}, value);
                            }
                        })
                    } else if (sendWay.curDeliveryType == 1 && Array.isArray(sendWay.receivePersons) && sendWay.receivePersons.length > 0) {
                        sendWay.receivePersons.forEach((value, index) => {
                            if (value.selected) {
                                that.sendWay = Object.assign({}, value);
                            }
                        })
                    }
                    that.sendWay = Object.assign({}, this.sendWay, {curDeliveryType: sendWay.curDeliveryType})
                }, 10)
            },
            selectAdress() {
                this.$router.push('/order/sendWay');
            },
            initTabBanner() {
                this.tabBanner = {
                    showNum: true,
                    showType: 'bracket',
                    list: [
                        {
                            id: 0,
                            name: '可用',
                            num: 0,
                            default: false,
                        },
                        {
                            id: 1,
                            name: '不可用',
                            num: 0,
                            default: false,
                        }
                    ]
                }
            },
            /*一个店铺下面包含的商品itemId*/
            getIncludeGoodsIds(storeId) {
                let that = this;
                let tempObj = {};
                let theSelectedStoreGoods = {};
                that.sureOrder.cartStoreInfos.forEach((value, index) => {
                    theSelectedStoreGoods.ids = [];
                    theSelectedStoreGoods.storeId = storeId;
                    theSelectedStoreGoods.goodsList = [];
                    value.cartItemInfos.forEach((cartItemInfoValue, cartItemInfoIndex) => {
                        tempObj = {
                            itemId: cartItemInfoValue.itemId,
                            stlyeName: cartItemInfoValue.stlyeName,
                            price: cartItemInfoValue.price,
                            buyNum:cartItemInfoValue.buyNum
                        };
                        theSelectedStoreGoods.ids.push(cartItemInfoValue.itemId);
                        theSelectedStoreGoods.goodsList.push(tempObj);
                    });
                    that.selectedStoreGoods.push(theSelectedStoreGoods);
                });
            },
            getSelectedStoreGoods(storeId) {
                /*获取当前店铺下的优惠券的id*/
                let that = this;
                let theSelectedStoreGoods = {};
                that.selectedStoreGoods.forEach((value, index) => {
                    if (value.storeId == storeId) {
                        theSelectedStoreGoods = value;
                    }
                })
                return theSelectedStoreGoods
            },
            showDiscountFn(storeId) {
                this.initTabBanner();
                let that = this;
                /*获取页面优惠商品信息*/
                this.getIncludeGoodsIds(storeId);
                let theSelectedStoreGoods = this.getSelectedStoreGoods(storeId);

                /*可用优惠券的商品id*/
                // 门店优惠券不可用判断：
                // 0、优惠券是否正常状态， 否的话，不可用，
                // 1、是否仅线下核销。是的话，不可用
                // 2、店铺采购商品中 是否有商品，不在优惠券指定商品范围内 有则不可用
                // 3、店铺商品购买总额 是否达到优惠券使用条件，否的话，不可用
                // 4、是否指定配送方式，是的话，判断当前配送方式是否正确，不对则不可用

                /*先制空*/
                this.discountlist.cantUseList = [];
                this.discountlist.canUseList = [];
                /*优惠券能否使用的判断*/
                this.sureOrder.cartStoreInfos.forEach((value, index) => {
                    if (value.storeId == storeId) {
                        that.discountMsg.storeId = storeId;
                        /*优惠券可用与不可用的数量*/
                        if (value.tradeTicketModels) {
                            value.tradeTicketModels.forEach((ticketValue, ticketIndex) => {
                                /*优惠券状态不正常*/
                                if (ticketValue.state != 0) {
                                    that.discountlist.cantUseList.push(ticketValue);
                                    /*仅线下核销*/
                                } else if (ticketValue.onlyOfflineUse) {
                                    that.discountlist.cantUseList.push(ticketValue);
                                    /*优惠券指定了商品范围*/
                                } else if (Array.isArray(ticketValue.canUseItemIds)) {
                                    /*店铺采购商品中全部都需要在优惠券指定商品范围内才可以使用优惠券（比较简单粗暴）*/
                                    let allBelong = true;
                                    theSelectedStoreGoods.ids.forEach((canUseItemIdValue, canUseItemIdIndex) => {
                                        if (!ticketValue.canUseItemIds.includes(canUseItemIdValue)) {
                                            allBelong = false;
                                        }
                                    });
                                    if (allBelong) {
                                        isCanUseDiscount(ticketValue,theSelectedStoreGoods);
                                    } else {
                                        that.discountlist.cantUseList.push(ticketValue);
                                    }
                                    /*全部商品可用的情况下*/
                                } else if (!ticketValue.canUseItemIds || ticketValue.canUseItemIds == null || ticketValue.canUseItemIds == 'null') {
                                    isCanUseDiscount(ticketValue,theSelectedStoreGoods);
                                    /*指定配送方式*/
                                } else if (Array.isArray(ticketValue.deliveryTypes)) {
                                    /*指定配送方式包含在当前配送方式*/
                                    if (ticketValue.deliveryTypes.includes(that.sendWay.curDeliveryType)) {
                                        that.discountlist.canUseList.push(ticketValue);
                                    } else {
                                        that.discountlist.cantUseList.push(ticketValue);
                                    }
                                } else {
                                    that.discountlist.canUseList.push(ticketValue);
                                }
                            })
                        }
                    }
                });

                this.tabBanner.list[0].num = that.discountlist.canUseList.length;
                this.tabBanner.list[1].num = that.discountlist.cantUseList.length;
                this.discountMsg.show = true;
                this.discountMsg = Object.assign({}, this.discountMsg);
                setTimeout(() => {
                    if (this.$refs.discountList) {
                        this.$refs.discountList.showSlideBottom();
                    }
                }, 150)
                function isCanUseDiscount(ticketValue,theSelectedStoreGoods) {
                    // 3、全部选购符合条件的商品的总额没有达到优惠券使用条件；
                    /*满减券：全部选购商品的总金额满足满减要求的就可以享受金额减免*/
                    /*折扣券：全部选购商品的折扣（全部商品都需要满足折扣券的使用范围）*/
                    /*增值券：未做*/
                    /*赠品券：符合条件即可赠予*/
                    /*TODO 等待做*/
                    /*计算当前店铺下所有选购商品的总价*/
                    let goodsTotal = 0;//这里计算的时候补考虑快递费的情况，即快递费另外再总价中加，这里可能会让用户产生疑惑
                    theSelectedStoreGoods.goodsList.forEach((goodsItem,goodIndex)=>{
                        goodsTotal += goodsItem.price * goodsItem.buyNum
                    });
                    goodsTotal = Math.floor(goodsTotal * 100) / 100;
                    /*总金额小于优惠券可使用条件金额*/
                    /*1满减券(代金券)/3折扣券/4赠品券*/
                    if ( ticketValue && (ticketValue.ticketType == 1 || ticketValue.ticketType == 3 || ticketValue.ticketType == 4)) {
                        /*可以使用优惠券的情况，限制了优惠券的使用金额且金额小于或等于店铺所选购商品金额 或者没有限制金额*/
                        let canUser = ticketValue && ticketValue.ticketContent && ((ticketValue.ticketContent.limitConsume
                            && ticketValue.ticketContent.consumePrice <= goodsTotal) ||  !ticketValue.ticketContent.limitConsume);
                        if( canUser ){
                            that.discountlist.canUseList.push(ticketValue);
                            console.log(that.discountlist.canUseList)
                        }else{
                            that.discountlist.cantUseList.push(ticketValue);
                            console.log(that.discountlist.cantUseList)
                        }
                        /*是否指定了配送方式*/
                    }  else if (Array.isArray(ticketValue.deliveryTypes)) {
                        /*指定配送方式包含在当前配送方式*/
                        if (ticketValue.deliveryTypes.includes( that.sendWay.curDeliveryType )) {
                            that.discountlist.canUseList.push(ticketValue);
                        } else {
                            that.discountlist.cantUseList.push(ticketValue);
                        }
                    } else {
                        that.discountlist.canUseList.push(ticketValue);
                    }
                }
            },
            cardItemFn(obj) {
                let cardItemMsg = {
                    condition: obj.ticketContent,
                };
                cardItemMsg = Object.assign({}, cardItemMsg, obj);
                return cardItemMsg
            },
            selectDisount(obj) {
                let that = this;
                that.tabBanner.list.forEach((value, index) => {
                    if (value.id == obj.id) {
                        that.discountMsg.tapId = obj.id;
                    }
                })
            },
            selectDisountItem(storeId,ticketValue){
                let that = this;
                that.sureOrder.cartStoreInfos.forEach((cartStoreInfoItem,cartStoreInfoIndex)=>{
                    if(cartStoreInfoItem.storeId == storeId && Array.isArray(cartStoreInfoItem.tradeTicketModels) && cartStoreInfoItem.tradeTicketModels.length > 0){
                        cartStoreInfoItem.tradeTicketModels.forEach((ticketItem,ticketIndex)=>{
                            if(ticketValue.ticketNum == ticketItem.ticketNum){
                                that.sureOrder.cartStoreInfos[cartStoreInfoIndex].defaultUseTicket = ticketItem;
                                that.sureOrder = Object.assign({},that.sureOrder);
                                that.$refs.discountList.clickBord()
                                that.closeSelectDiscount();
                            }
                        })
                    }
                })
            },
            /*下拉刷新*/
            refresh(done) {
                let that = this;
                setTimeout(() => {
                    /*TODO 刷新数据*/
                    // this.$emit('getSubCommentList');
                    that.$refs.myscroller.finishPullToRefresh();//刷新完毕关闭刷新的转圈圈
                }, 500)
            },
            /*下拉加载*/
            infinite() {
                let that = this;
                if (that.$refs.myscroller.finishInfinite) {
                    that.$refs.myscroller.finishInfinite(true);//刷新完毕关闭刷新的转圈圈
                    setTimeout(() => {
                        // this.getUserCardList(true);
                        that.$refs.myscroller.finishPullToRefresh();//刷新完毕关闭刷新的转圈圈
                    }, 500)
                }
            },
            /*选择支付方式*/
            selectPayWay() {
                /*TODO 这里要显示弹出框，选择支付方式*/
                let url = `${this.NW_API_API_LOCALE_VERSION}/capital/user/${this.currentUser && this.currentUser.userId ? this.currentUser.userId : 0}/get`;
                this.xurl.getLoading(url).then((data) => {
                    this.payWay.accountMoney = data.result.cashAmount;
                    this.payWay.payMoney = this.buyBarMsg.payMoney.money;
                    this.payWayAlert = true;
                    setTimeout(() => {
                        if (this.$refs.payWay && this.$refs.payWay.showSlideBottom) {
                            this.$refs.payWay.showSlideBottom();
                        }
                    }, 150)
                });
            },
            surePayWay(payWay) {
                if (payWay == 'ACCOUNT') {
                    this.inputPassword = true;
                    this.payWayAlert = false;
                    if(this.$refs.inputPassword && this.$refs.inputPassword.showSlideBottom){
                        this.$refs.inputPassword.showSlideBottom();
                    }
                } else {
                    this.toPay(payWay);
                }
            },
            colsePayWay() {
                this.$refs.payWay.clickBord();
            },
            closeInputPassword() {
                this.payWayAlert = true;
                this.inputPassword = false;
                // this.$refs.inputPassword.clickBord();
            },
            toPay(payWay, password) {
                let that = this;
                let buyStoreInfos = [];
                let passwordMd5 = ''
                if (password) {
                    passwordMd5 = MD5(password);//支付密码
                }
                let url = '';//请求地址
                let tempObj = {};
                let buyItemObj = {};
                payWay = payWay || XPay.getPayChannel();
                let openId = 0;
                if(this.currentThird && this.currentThird.openId){
                    openId = this.currentThird.openId;
                }
                that.sureOrder.cartStoreInfos.forEach((cartStoreInfoValue, cartStoreInfoIndex) => {
                    let buyItemInfos = [];
                    cartStoreInfoValue.cartItemInfos.forEach((cartItemInfoValue, cartItemInfoIndex) => {
                        buyItemObj = {
                            "itemId": cartItemInfoValue.itemId,       //---------商品ID
                            "styleName": cartItemInfoValue.styleName,    //---------购买款式
                            "buyNum": cartItemInfoValue.buyNum,         //---------购买数量
                        }
                        buyItemInfos.push(buyItemObj);
                    });
                    tempObj = {
                        "storeId": cartStoreInfoValue.storeId,          //---------------店铺ID
                        "ticketNum": cartStoreInfoValue.defaultUseTicket && cartStoreInfoValue.defaultUseTicket.ticketNum ? cartStoreInfoValue.defaultUseTicket.ticketNum : '' ,       //---------------使用的优惠券号
                        "buyerMessage": cartStoreInfoValue.leaveMessage || '',      //---------------用户备注
                        "buyItems": buyItemInfos,
                    }
                    buyStoreInfos.push(tempObj);
                })

                let params = {
                    "terminalType": 6,   //-----------------终端类型： 5.好看好玩APP; 6.好看好玩H5;
                    "userId": that.currentUser && that.currentUser.userId ? that.currentUser.userId : 0,      //-----------------买家用户ID
                    "deliveryType": that.sendWay.curDeliveryType,   //-----------------配送类型 0:自提  1：快递
                    "deliveryId": that.sureOrder.deliveryId,    //-----------------配送ID
                    "buyStoreInfos": buyStoreInfos,
                    // "payPwd": password //--------用户的支付密码, MD5加密
                };
                switch (payWay) {
                    case 'ACCOUNT'://账户支付
                        params = Object.assign({}, params, {"payPwd": passwordMd5});
                        url = `${this.NW_API_API_LOCALE_VERSION}/trade/confirm/order/capital/pay`;
                        break;
                    case 'WECHAT'://微信支付
                        let exsitPayOpenidUrl = '/h5/prepay/deposit';
                        if(openId){
                            exsitPayOpenidUrl = `/h5/prepay/deposit?payOpenId=${openId}`;
                        }
                        url = `${this.NW_API_API_LOCALE_VERSION}/${payWay}${exsitPayOpenidUrl}`;
                        break;
                    case 'ALIPAY'://支付宝支付
                        url = `${this.NW_API_API_LOCALE_VERSION}/${payWay}/h5/prepay/deposit`;
                        break;
                    default :
                        url = `${this.NW_API_API_LOCALE_VERSION}/${payWay}/h5/prepay/deposit`;
                        break;
                }
                this.xurl.postDataJsonLoading(url, params).then((data) => {
                    if (data.success) {
                        /*这里跳转的页面还没有*/
                        if (payWay == "ACCOUNT") {
                            this.accountPaySuccess(data);
                        } else if (payWay == "WECHAT") {
                            this.payForWechat(data);
                        } else if (payWay == "ALIPAY") {
                            this.payForAlipay(data);
                        }
                    } else if (data.errMsg) {
                        if (this.$refs.inputPasswordAlert) {
                            this.$refs.inputPasswordAlert.passwordWrong = true;
                        }
                        that.$root.$emit('toast', {msg: data.errMsg});
                    } else {
                        that.$root.$emit('toast', {msg: '支付失败'});
                    }
                })
            },
            accountPaySuccess(data) {
                if (this.$refs.payWay) {
                    this.payWayAlert = false;
                } else if (this.$refs.inputPassword) {
                    this.inputPassword = false;
                }
                this.$router.push({path: '/order/list', query: {tabId: 0}})
                this.$root.$emit('toast', {msg: '支付成功'});
            },
            payForWechat(data) {
                if (data.result.href) {
                    window.location.href = data.result.href;
                } else if (data.result.prepay) {
                    XPay.toPay(data.result.prepay)
                }else if(data.result.free){
                    this.$router.push({path:'/order/list',query:{tabId:0}})
                }
            },
            payForAlipay(data) {
                XPay.toPay(data.result.prepay);
            },
        },
        components: {
            'select-cart': () => import('./components/SelectCart'),
            'buy-bar': () => import('../../components/commonActModel/buyBar/goodsBuyBar'),
            'pay-way': () => import('./components/PayWay'),
            'input-password': () => import('./components/InputPassWord'),
            'slide-bottom': () => import('../../components/commonComponents/slideBottom/SlideBottom'),
            'card-item': () => import('../../components/commonComponents/card/CartItem'),
            'tap-banner': () => import('../../components/commonComponents/tap/Banner'),
            "no-data": () => import("../../components/commonActModel/noData/NoData"),
        }
    }
</script>

<style scoped lang="scss">
    .coupons1_0-list {
        padding: .1rem .1rem .5rem;
        width: 100%;
        box-sizing: border-box;
        background-color: #f5f5f5;
        margin-top: .4rem;

    }
    .coupons1_0-list /deep/{
        .no-wcomment{
            padding: .5rem 0;
        }
    }
    .sure-order .input-password-wrap /deep/ .slide-bottom-transition {
        height: 2rem;
    }

    .coupons1_0-item {
        margin-bottom: .1rem;
        height: auto;
        width: 100%;
        position: relative;
    }

    .sure-order /deep/ {
        .slide-bottom-transition {
            height: 4rem;
            max-height: 80%;
        }
    }

    .user-box {
        background-color: #FCFCFC;
        padding: .15rem;
        margin-bottom: .1rem;
    }

    .user-other-msg {
        font-size: .14rem;
        color: #333;
    }

    .user-wmsg {
        width: 100%;
        position: relative;
        left: 50%;
        transform: translateX(-50%);
        -webkit-border-radius: .05rem;
        -moz-border-radius: .05rem;
        border-radius: .05rem;
        background-color: #fff;
        padding: .15rem;
        -webkit-box-shadow: 0 0 .1rem 0 rgba(204, 204, 204, .4);
        box-shadow: 0 0 .1rem 0 rgba(204, 204, 204, .4);
    }

    .user-msg {
        padding-right: .48rem;
    }

    .user-address {
        font-size: .13rem;
        color: #666;
        line-height: .2rem;
        padding-top: .15rem;
    }

    .user-name {
        color: #333;
        font-size: .14rem;
        font-weight: bold;
    }

    .send-way-text {
        background-color: rgba(153, 153, 153, .2);
        color: #999;
        font-size: .12rem;
        display: inline-block;
        width: .34rem;
        height: .15rem;
        text-align: center;
        line-height: .16rem;
        -webkit-border-radius: .25rem;
        -moz-border-radius: .25rem;
        border-radius: .25rem;
    }

    .send-way-text.send-active {
        background-color: rgba(109, 145, 223, .2);
        color: #6D91DF;
    }

    .send-way-text.self-extract {
        background-color: rgba(255, 51, 51, .2);
        color: #FF3333;
    }

    .sure-order {
        background-color: #f5f5f5;
    }

    .card-tab {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 1;
        width: 100%;
        height: .4rem;
        line-height: .4rem;
        background-color: #fff;
        border-top-right-radius: .1rem;
        border-top-left-radius: .1rem;
    }

    .tab-item {
        display: inline-block;
        height: .4rem;
    }

    .active.tab-item {
        border-bottom: 2px solid #5D89E8;
    }
    .disabled-ticket /deep/{
        .coupons1_0-money,.coupons1_0-date,.coupons1_0-use-wcondition,.coupons1_0-reduce,.coupons1_0-condition{
            color: #CCCCCC!important;
        }
    }
</style>